import { Component, OnInit } from '@angular/core';
import { User, UserManage } from "../../../entity/user.model";
import { AuthService } from "../../../service/auth.service";
import { Router } from "@angular/router";
import { ApplicationService } from "../../../service/application.service";
import { UserService } from '../../../service/user.service';
import { UserFarm } from '../../../entity/user-farm.model';
import { UserProfile } from '../../../entity/user-profile.model';
import { FactoryService } from '../../../service/factory.service';

@Component({
  selector: 'app-user-session',
  templateUrl: './user-session.component.html',
  styleUrls: ['./user-session.component.css']
})
export class UserSessionComponent implements OnInit {
  public userInfo: User;
  showSetting: boolean = false;
  userManage: UserManage;
  userName: string = '';
  realName: string = '';
  passWord: string = '';
  email: string = '';
  telNo: string = '';
  faxNo: string = '';
  confirmPasswords: string = '';
  // basicUserFarmList: UserFarm[] =[];
  sysUser: User;
  sysProfile: UserProfile;
  icon: string;
  sex: number;

  file: File;
  localhostPath: string;

  //错误对象
  realNameError: boolean = false;
  passWordError: boolean = false;
  confirmPasswordError: boolean = false;
  emailError: boolean = false;
  telNoError: boolean = false;
  faxNoError: boolean = false;
  showSavebutton: boolean = true;

  showImg: boolean = false;
  showGirl: boolean = false;

  constructor(
    public authService: AuthService,
    public router: Router,
    private application: ApplicationService,
    private userService: UserService,
    private factoryService: FactoryService,
  ) { }
  private curWwwPath: string;
  private pathName: string;
  private pos: number;
  ngOnInit() {

    this.curWwwPath = window.location.href;
    this.pathName = window.location.pathname;
    this.pos = this.curWwwPath.indexOf(this.pathName);
    this.localhostPath = this.curWwwPath.substring(0, this.pos);
    this.localhostPath = (this.localhostPath == 'http://localhost:4200') ? this.localhostPath + '/assets/images' : this.localhostPath + '/img';

    this.icon = this.application.currentUserProfile.icon;
    this.userInfo = this.application.currentUser;
    this.sex = this.application.currentUserProfile.sex;
    this.userName = this.application.currentUser.userName;
    this.realName = this.application.currentUserProfile.realName;
    this.passWord = this.application.currentUser.passWord;
    this.email = this.application.currentUserProfile.email;
    this.telNo = this.application.currentUserProfile.telNo;
    this.faxNo = this.application.currentUserProfile.faxNo;
    this.initData()
  }

  initData() {
    this.icon = this.application.currentUserProfile.icon;
    this.sex = this.application.currentUserProfile.sex;
    if (this.icon) {
      this.showImg = true;
    } else {
      this.showImg = false;
      if (this.sex == 0) {
        this.showGirl = true;
      } else {
        this.showGirl = false;
      }
    }
  }

  /**
   * 退出
   * 
   * @memberof UserSessionComponent
   */
  public loginOut() {
    this.application.clear();
   // window.sessionStorage.clear();
    this.router.navigate(["/login"]);
  }

  /**
   * 点击设置
   * 
   * @memberof UserSessionComponent
   */
  public setTings() {
    this.showSetting = true;
    this.icon = this.application.currentUserProfile.icon;

    this.userService.getUsersByuserId(this.application.currentUser.userId)
      .then(res => {
        if (!res) { return false; };
        this.userManage = res;
      })
      .catch(err => { console.log(err) })
  }
  /**
   * 保存
   * 
   * @memberof UserSessionComponent
   */
  public save() {
    this.showSetting = false;

    this.userManage.sysUser.passWord = this.passWord;
    this.userManage.sysUser.realName = this.realName;
    this.userManage.sysUser.userName = this.userName;
    this.userManage.sysProfile.email = this.email;
    this.userManage.sysProfile.faxNo = this.faxNo;
    this.userManage.sysProfile.realName = this.realName;
    this.userManage.sysProfile.telNo = this.telNo;


    if (this.file) {
      this.factoryService.upFile(this.file)
        .then(res => {
          if (res) {
            let currentUserProfile = JSON.parse(window.sessionStorage.getItem('currentUserProfile'));
            currentUserProfile.icon = res;
            window.sessionStorage.setItem('currentUserProfile', JSON.stringify(currentUserProfile))
            this.icon = this.application.currentUserProfile.icon;
            this.userManage.sysProfile.icon = this.icon;
            this.userService.myUpdate(this.userManage)
              .then(res => {
                if (res) {
                  return true;
                }
              })
            return true;
          }
        })
    } else {
      this.userService.myUpdate(this.userManage)
        .then(res => {
          if (res) {
            return true;
          }
        })
    }
    this.initData();
  }
  /**
   * 关闭按钮
   * 
   * @memberof UserSessionComponent
   */
  public close() {
    this.showSetting = false;
    this.userName = this.application.currentUser.userName;
    this.realName = this.application.currentUserProfile.realName;
    this.passWord = this.application.currentUser.passWord;
    this.email = this.application.currentUserProfile.email;
    this.telNo = this.application.currentUserProfile.telNo;
    this.faxNo = this.application.currentUserProfile.faxNo;
  }
  onblur(num) {
    switch (num) {
      case 1:
        let reg = new RegExp("^[\u4e00-\u9fa5a-zA-Z0-9]+$");
        if (this.realName.length > 0) {
          if (reg.test(this.realName)) {
            this.realNameError = false;
          }
        } else {
          this.realNameError = true;
        }
        this.showSaveBtn()
        break;
      case 2:
        if (this.passWord.length > 0 && this.passWord.length <= 50) {
          this.passWordError = false;
        } else {
          this.passWordError = true;
        }
        this.showSaveBtn()
        break;
      case 3:
        if (this.passWord !== this.confirmPasswords) {
          this.confirmPasswordError = true;
        } else {
          this.confirmPasswordError = false;
        }
        this.showSaveBtn()
        break;
      case 4:
        let emailReg = new RegExp("^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$");
        if (this.email.length > 0 && this.email.length <= 20) {
          if (emailReg.test(this.email)) {
            this.emailError = false;
          } else {
            this.emailError = true;
          }
        } else {
          this.emailError = true;
        }
        this.showSaveBtn()
        break;
      case 5:
        let telNoReg = new RegExp("^(1)([3,4,5,7,8])([0-9]{9})$");
        if (telNoReg.test(this.telNo)) {
          this.telNoError = false;
        } else {
          this.telNoError = true;
        }
        this.showSaveBtn();
        break;
      default:
        let faxNoReg = new RegExp("^([0-9]{3,4}-)?[0-9]{7,8}$");
        if (faxNoReg.test(this.faxNo)) {
          this.faxNoError = false;
        } else {
          this.faxNoError = true;
        }
        this.showSaveBtn()

    }
  }

  showSaveBtn() {
    if (this.realNameError || this.passWordError || this.emailError || this.telNoError || this.faxNoError) {
      this.showSavebutton = false;
    } else {
      this.showSavebutton = true;
    }
  }

  onUpload(ev) {
    this.file = ev.files;

  }
  onRemove(ev) {
    this.file = null;
  }
  onDelete() {
    //此处应该调用服务删除img文件夹中的文件。（等杨科婚假后写服务）
    // let currentUserProfile = JSON.parse(window.sessionStorage.getItem('currentUserProfile'));
    // currentUserProfile.icon = '';
    // window.sessionStorage.setItem('currentUserProfile', JSON.stringify(currentUserProfile))
    // this.icon = this.application.currentUserProfile.icon;
    // this.showImg = false;
    this.userManage.sysUser.passWord = this.passWord;
    this.userManage.sysUser.realName = this.realName;
    this.userManage.sysUser.userName = this.userName;
    this.userManage.sysProfile.email = this.email;
    this.userManage.sysProfile.faxNo = this.faxNo;
    this.userManage.sysProfile.realName = this.realName;
    this.userManage.sysProfile.telNo = this.telNo;
    this.userManage.sysProfile.icon = '';
    this.userService.myUpdate(this.userManage)
      .then(res => {
        if (res) {
          let currentUserProfile = JSON.parse(window.sessionStorage.getItem('currentUserProfile'));
          currentUserProfile.icon = '';
          window.sessionStorage.setItem('currentUserProfile', JSON.stringify(currentUserProfile))
          this.icon = this.application.currentUserProfile.icon;
          this.showImg = false;
          return true;
        }
      })
  }

}


// WEBPACK FOOTER //
// ./src/app/module/navigation/user-session/user-session.component.ts